import React from 'react';
import { Expense, CATEGORY_CONFIG } from '../types';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';

interface ExpenseListProps {
  expenses: Expense[];
  onDelete: (id: string) => void;
}

const ExpenseList: React.FC<ExpenseListProps> = ({ expenses, onDelete }) => {
  // 按日期对消费记录进行分组
  const groupByDate = (expenses: Expense[]) => {
    const grouped: Record<string, Expense[]> = {};
    
    expenses.forEach(expense => {
      if (!grouped[expense.date]) {
        grouped[expense.date] = [];
      }
      grouped[expense.date].push(expense);
    });
    
    return Object.entries(grouped)
      .sort(([dateA], [dateB]) => new Date(dateB).getTime() - new Date(dateA).getTime());
  };

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    
    if (date.toDateString() === today.toDateString()) {
      return '今天';
    } else if (date.toDateString() === yesterday.toDateString()) {
      return '昨天';
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  };

  const handleDelete = (id: string) => {
    onDelete(id);
    toast('消费记录已删除');
  };

  // 安全地格式化金额，处理可能为undefined的情况
  const formatAmount = (amount: number | undefined): string => {
    if (amount === undefined || amount === null) {
      return '¥0.00';
    }
    return `¥${amount.toFixed(2)}`;
  };

  const groupedExpenses = groupByDate(expenses);

  // 计算每日总金额
  const calculateDailyTotal = (expenses: Expense[]): number => {
    return expenses.reduce((total, expense) => {
      // 确保amount是有效的数字
      const amount = typeof expense.amount === 'number' ? expense.amount : 0;
      return total + amount;
    }, 0);
  };

  return (
    <div className="space-y-6">
      {Object.entries(groupedExpenses).map(([date, dayExpenses]) => (
        <div key={date} className="space-y-3">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold text-gray-700 dark:text-gray-300">
              {formatDate(date)}
            </h3>
            <span className="text-blue-500 font-medium">
              {formatAmount(calculateDailyTotal(dayExpenses))}
            </span>
          </div>
          <div className="space-y-3">
            {dayExpenses.map(expense => {
              // 获取类别配置，如果不存在则使用默认配置
              const categoryConfig = CATEGORY_CONFIG[expense.category as keyof typeof CATEGORY_CONFIG] || {
                color: 'bg-gray-500',
                icon: 'fas fa-question-circle',
                name: '未知'
              };
              
              return (
                <motion.div
                  key={expense.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.3 }}
                  className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-md border border-gray-100 dark:border-gray-700"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <div className={`p-2 rounded-full ${categoryConfig.color}`}>
                        <i className={`${categoryConfig.icon} text-white`}></i>
                      </div>
                      <div>
                        <p className="font-medium text-gray-900 dark:text-gray-100">{expense.description}</p>
                        <div className="flex items-center mt-1">
                          <span className="text-sm text-gray-500 dark:text-gray-400">
                            {categoryConfig.name}
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <span className="font-bold text-lg text-gray-900 dark:text-gray-100">
                        {formatAmount(expense.amount)}
                      </span>
                      <button
                        onClick={() => handleDelete(expense.id)}
                        className="text-gray-400 hover:text-red-500 transition-colors"
                        aria-label="删除"
                      >
                        <i className="fas fa-trash-alt"></i>
                      </button>
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </div>
        </div>
      ))}
      
      {expenses.length === 0 && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="flex flex-col items-center justify-center py-16 text-center"
        >
          <div className="bg-gray-100 dark:bg-gray-800 p-4 rounded-full mb-4">
            <i className="fas fa-receipt text-gray-400 text-2xl"></i>
          </div>
          <h3 className="text-lg font-medium text-gray-700 dark:text-gray-300 mb-1">暂无消费记录</h3>
          <p className="text-gray-500 dark:text-gray-400 max-w-md">
            您还没有添加任何消费记录，点击下方的"+"按钮开始记录您的消费吧！
          </p>
        </motion.div>
      )}
    </div>
  );
};

export default ExpenseList;